package org.pinda.network.auth;

import java.io.DataOutputStream;
import java.io.IOException;

import org.pinda.network.ConnectionType;
import org.pinda.network.PacketUtils;
import org.pinda.network.util.Stream;
import org.pinda.server.Loggers;
import org.pinda.server.ServerClient;

public class PacketHandshake extends IAuthPacket {
	
	public static final short ID = 0;
	
	private ConnectionType connectionType;
	
	public PacketHandshake() {
		
	}
	
	public PacketHandshake(ConnectionType connectionType) {
		this.connectionType = connectionType;
	}

	@Override
	public void write(DataOutputStream outStream) throws IOException {
		PacketUtils.writeString(outStream, connectionType.toString());
	}

	@Override
	public void read(Stream inStream) throws IOException {
		String typeName = PacketUtils.readString(inStream);
		for(ConnectionType connectionType : ConnectionType.values()) {
			if(typeName.equals(connectionType.toString())) {
				this.connectionType = connectionType;
				break;
			}
		}
	}
	
	@Override
	public void processServer(ConnectionType connectionType, ServerClient client) throws IOException {
		if(connectionType.equals(this.connectionType)) {
			Loggers.auth().info(client + " passed handshake for " + connectionType);
			client.sendPacket(new PacketHandshakeResponse(true));
		} else {
			Loggers.auth().warning(client + " passed handshake for " + connectionType);
			client.sendPacket(new PacketHandshakeResponse(false));
			client.close();
		}
	}

	@Override
	public short getId() {
		return ID;
	}

	@Override
	public int getLength() {
		return PacketUtils.packetLengthString(connectionType.toString());
	}

}
